﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace XfTechOAWeb.Infrastructure.Filters
{
    /// <summary>
    /// 全局Action过滤器-在日志文件中输出Action处理耗时
    /// </summary>
    public class GlobalLogActionFilter : IAsyncActionFilter
    {
        private ILogger<GlobalLogActionFilter> _logger;
        public GlobalLogActionFilter(ILogger<GlobalLogActionFilter> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 过滤器的处理
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            if(context.ActionDescriptor.EndpointMetadata.Any(m=>m.GetType()==typeof(NoLogAttribute)))
            {
                await next(); //不进行记录，直接调用下一个方法
                return;
            }

            //开启秒表计时
            var sw = new Stopwatch();
            sw.Start();
            //执行方法处理
            var result = await next(); //回调我们写的控制器的方法（Action）
            //结束秒表计时
            sw.Stop();

            var actionName = context.ActionDescriptor.AttributeRouteInfo.Template.ToLower();
            _logger.LogInformation($"执行了{actionName}方法，用时{sw.ElapsedMilliseconds}毫秒");
        }
    }
}
